import React, {FC, useContext, useRef} from 'react';
import "./index.less";
import {Button, Flex, Form, Input, InputRef, message, Tooltip, Typography} from "antd";
import {CloseSquareFilled, LockOutlined, MailOutlined, SafetyOutlined, UserOutlined} from "@ant-design/icons";
import {FormattedMessage, history, Link, useIntl} from "@@/exports";
import KfCaptchaInput from "@kf-web-library/forms/es/serviceComponents/KfCaptcha/KfCaptchaInput";
import {nanoid} from "nanoid";
import {DEFAULT_LOGIN_PATH as LOGIN_PATH, DEFAULT_REGISTER_PATH as REGISTER_PATH} from "@kf-web-library/utils/es/constants";
import {HxConfigContext} from "@/layouts/HxConfigContext";
import querystring from "query-string";
import {useRequest} from "ahooks";
import * as API from "@/services";
import {StatelessCaptchaReq} from "@/services";
import lodash from "lodash";
import {KfCaptchaAction} from "@kf-web-library/forms";
import {CommonRegex} from "kf-web-library";
import KfCountdownButton from "@kf-web-library/components/es/KfCountdownButton/KfCountdownButton";
import HxIcon from "@/components/HxIcon";

interface ForgotPageProps {
}


const ForgotPage: FC<ForgotPageProps> = (props) => {
  const {authedRedirect} = useContext(HxConfigContext);
  const [form] = Form.useForm();
  const intl = useIntl();

  const captchaRef = useRef<KfCaptchaAction | undefined>();
  const vCodeInputRef = useRef<InputRef>(null);

  const forgotReq = useRequest((p) => API.forgot(p), {
    manual: true,
    onError: (e: any) => {
      if (e?.response?.data?.bizcode == 409011) {
        vCodeInputRef.current?.focus?.();
      }
    },
    onSuccess: (resp) => {
      if (resp.flag) {
        history.push({
          pathname: `/login`,
          search: authedRedirect ? querystring.stringify({redirect: authedRedirect}) : "",
        });
      }
    }
  })

  const sendVerificationCodeReq = useRequest((emailOrMobile: string, captcha: StatelessCaptchaReq) => API.sendVerificationCode({
    emailOrMobile,
    captcha,
    verificationCodeType: "FORGOT_PWD",
  }), {
    manual: true,
    onError: (e: any) => {
      if (e?.response?.data?.bizcode == 409006) {
        captchaRef.current?.refresh();
      }
      captchaRef.current?.focus?.();
    },
    onSuccess: (resp, p) => {
      if (resp.flag) {
        if (lodash.isString(resp.data)) {
          //测试环境, 验证码会直接返回出来
          form.setFieldValue("verificationCode", resp.data)
        }
        message.success(<>已发送至<Typography.Text type="success">{p[0]}</Typography.Text>，请注意接收</>);
      }
    }
  })

  return (
    <div className={"forgot-page-container"}>
      <div className={"forgot-page-title"}>
        <FormattedMessage id="text.forgot"/>
      </div>
      <Form
        form={form}
        className={"tooltip-feedback-form"}
        scrollToFirstError={{
          focus: true,
        }}
        feedbackIcons={({errors}) => ({
          error: (
            <Tooltip
              key="tooltipKey"
              title={errors?.map((error) => <div key={nanoid()}>{error}</div>)}
              color="red"
            >
              <CloseSquareFilled/>
            </Tooltip>
          ),
        })}
        onFinish={(values) => {
          forgotReq.run(lodash.omit(values, ["captcha"]));
        }}
      >
        <Form.Item
          name="emailOrMobile"
          help=""
          hasFeedback={true}
          rules={[
            {required: true, message: intl.formatMessage({id: `validation.emailOrMobile_require`})},
            () => ({
              validator(_, value) {
                if (!value) return Promise.resolve();
                if (!CommonRegex.EMAIL_NUMBER_REGEX.test(value) && !CommonRegex.CHINA_MOBILE_NUMBER_REGEX.test(value)) {
                  return Promise.reject(intl.formatMessage({id: `validation.emailOrMobile_require`}));
                }
                return Promise.resolve();
              },
            }),
          ]}

        >
          <Input prefix={<UserOutlined />} size={"large"} placeholder={intl.formatMessage({id: `validation.emailOrMobile_require`})}/>
        </Form.Item>
        <Form.Item
          name="captcha"
          help=""
          hasFeedback={true}
          rules={[{required: true, message: intl.formatMessage({id: `validation.captcha_require`})}]}
        >
          <KfCaptchaInput actionRef={captchaRef}
                          bizType={"FORGOT_PWD"}
                          prefix={<SafetyOutlined />} size={"large"}
                          placeholder={intl.formatMessage({id: `validation.captcha_require`})}
          />
        </Form.Item>

        <Form.Item noStyle shouldUpdate={true}>
          {({getFieldValue}) => {
            const emailOrMobile = getFieldValue("emailOrMobile");
            const captcha = getFieldValue("captcha");
            const enabledSendVerificationCode = emailOrMobile?.length > 5 && captcha?.input?.length > 1;

            return (
              <Form.Item help="" style={{marginBottom: 56}}>
                <Flex vertical={false} gap={6}>
                  <Form.Item
                    name="verificationCode"
                    help=""
                    noStyle
                    hasFeedback={true}
                    // extra="系统已经发送验证码到填写的邮箱，若未收到验证码，请到邮件垃圾箱中查找一下。"
                    rules={[{
                      required: true,
                      message: intl.formatMessage(
                        {id: `validation.verificationCode_require`},
                        {text: intl.formatMessage({id: "text.email-or-mobile"})}
                      )
                    }]}
                  >
                    <Input ref={vCodeInputRef} maxLength={6}
                           prefix={<HxIcon type={"hxicon-yanzhengma"}/>}
                           size={"large"}
                           placeholder={
                             intl.formatMessage(
                               {id: `validation.verificationCode_require`},
                               {text: intl.formatMessage({id: "text.email-or-mobile"})}
                             )
                           }
                    />
                  </Form.Item>

                  <KfCountdownButton color="primary"
                                     variant="filled"
                                     size={"large"}
                                     disabled={!enabledSendVerificationCode}
                                     style={{width: 160, fontSize: 16}}
                                     onClick={() => {
                                       /*if (!emailOrMobile) {
                                         message.error("请先输入手机/邮箱号");
                                         return;
                                       }*/
                                       return new Promise((resolve, reject) => {
                                         sendVerificationCodeReq.runAsync(emailOrMobile, captcha)
                                           .then(resp => {
                                             return resp.flag ? resolve() : reject()
                                           }).catch((error) => {
                                             reject();
                                             form.setFieldValue("captcha", "")
                                             captchaRef.current?.focus?.();
                                           }
                                         )
                                       })
                                     }}
                  >
                    <FormattedMessage id="text.send-verification-code"/>
                  </KfCountdownButton>
                </Flex>
              </Form.Item>
            )
          }}

        </Form.Item>


        <Form.Item
          name="passwd"
          help=""
          hasFeedback={true}
          extra={intl.formatMessage({id: `validation.passwd_pattern`})}
          rules={[
            {required: true, message: intl.formatMessage({id: `validation.passwd_require`})},
            {
              pattern: CommonRegex.ACCOUNT_PWD_REGEX,
              message: intl.formatMessage({id: `validation.passwd_pattern`}),
            }
          ]}
        >
          <Input.Password prefix={<LockOutlined/>} size={"large"} placeholder={intl.formatMessage({id: `validation.passwd_require`})}/>
        </Form.Item>
        <Form.Item
          name="rePasswd"
          help=""
          hasFeedback={true}
          rules={[
            {required: true, message: intl.formatMessage({id: `validation.rePasswd_require`})},
            ({getFieldValue}) => ({
              validator(rule, value) {
                if (!value || getFieldValue('passwd') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(intl.formatMessage({id: `validation.rePasswd_same`}));
              },
            }),
          ]}
        >
          <Input.Password prefix={<LockOutlined/>} size={"large"} placeholder={intl.formatMessage({id: `validation.rePasswd_require`})}/>
        </Form.Item>
        <Form.Item style={{marginTop: 24}}>
          <Button
            className={'login-submit-btn'}
            type="primary"
            htmlType="submit"
            size={"large"}
            block={true}
            loading={forgotReq.loading}
          >
            <FormattedMessage id="text.submit"/>
          </Button>
        </Form.Item>

        <Form.Item>
          <Flex vertical={false} gap={6} justify={"space-between"}>
            <div>
              <FormattedMessage
                id="text.account-desc2"
                values={{
                  btn: (
                    <Link to={{
                      pathname: LOGIN_PATH,
                      search: authedRedirect ? querystring.stringify({redirect: authedRedirect}) : "",
                    }}>
                      <FormattedMessage id="text.login"/>
                    </Link>
                  )
                }}
              />
            </div>
            <div>
              <FormattedMessage
                id="text.account-desc1"
                values={{
                  btn: (
                    <Link to={{
                      pathname: REGISTER_PATH,
                      search: authedRedirect ? querystring.stringify({redirect: authedRedirect}) : "",
                    }}>
                      <FormattedMessage id="text.register"/>
                    </Link>
                  )
                }}
              />

            </div>
          </Flex>
        </Form.Item>
      </Form>
    </div>
  );
};

export default ForgotPage;
